Django学习笔记六:form表单实现评论(检验数据合法性)

您所在的位置:网站首页 in a row的意思 Django学习笔记六:form表单实现评论(检验数据合法性)

Django学习笔记六:form表单实现评论(检验数据合法性)

#Django学习笔记六:form表单实现评论(检验数据合法性)| 来源: 网络整理| 查看: 265

最近一直想给博客更新一个模板,找了好多的静态模板,不知道怎么用,这几天特意花点时间在这个事情上,主要是静态文件的存放路径,好复杂呀,花了近两天时间才豁然开朗,特找了一个模板放在博客上,同时完善了博客的评论功能。 静态模板来自点击打开链接(花了我5个大洋换了500个积分,然而就用了20个积分生气)

运行效果

先上图看看效果:(是不是比之前的好看多了)

替换模板是个繁琐的项目。在这里就不多记录啦。 主要记录学习到了评论功能的实现。 评论功能作为单独的一个功能,把它作为一个单独的app,关于django框架设计的基本流程都是一样的: 设计数据库(M)-设计模型(V)-编写模板(T) 省略前面的建立app

评论功能分析 属性(5) 姓名,邮箱,电话,评论内容,创建时间关系 一篇文章可以有多个评论 一个评论只能是一篇文章 so: 文章-评论 一对多 知道了属性和关系,下面就很好设计了 数据库设计 # -*-coding:utf -*- from django.db import models # Create your models here. class Comment(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=255) phone = models.CharField(max_length=20) text = models.TextField() created_time = models.DateTimeField(auto_now_add=True) article = models.ForeignKey('blog.Article') def __str__(self): return self.text[:20] 设计评论表单模板

通常提交评论时需要检验评论者的邮箱,电话等内容是否正确,这里用到了django中form表单的功能,功能具体实现流程: 下面就是将流程转换为代码:

评论表单 comments/forms.py # -** coding:utf-8 -*- from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'email', 'phone','text'] 绑定url和视图函数 comments/urls.py from django.conf.urls import url from . import views app_name = 'comments' urlpatterns = [ url(r'^comment/article/(?P[0-9]+)/$', views.article_comment, name='article_comment') ] 视图函数 comments/views.py # -*- coding:utf-8 -*- from django.shortcuts import render, get_object_or_404, redirect from blog.models import Article from .models import Comment from .forms import CommentForm # Create your views here. def article_comment(request, article_id): #获取文章存在是获取给post, 反之返回404页面 article = get_object_or_404(Article, id = article_id) #POST提交表单 if requesthod == 'POST': #生成表单 form = CommentForm(request.POST) #django自动检验表单的内容是否合法 if form.is_valid(): #合法生成comment实例 comment = form.save(commit = False) comment.article = article comment.save() return redirect(article) else: #不合法 comment_list= article.comment_set.all() context = {'article':article,'form':form,'comment_list':comment_list} return render(request, 'blog/detail.html', context=context) #无提交命令,重定向到文章详情页 return redirect(article)

因为要将文章的评论加载在博客详情的页面中,这里的修改就是为了更新文章详情页,使其加载评论。

blog/view.py def detail(request,id): article = get_object_or_404(Article,id=id) article.body = markdown.markdown(article.body, extensions = [ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = article.comment_set.all() context = { 'article':article, 'form':form, 'comment_list':comment_list } return render(request, 'detail.html', context=context) 模型的设计

通过post方法提交表单。

templates/detail.html 发表评论 {% csrf_token %}


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3